<template>
    <Dialog ref="dialogRef" :title="title" @confirm="submit" :isCancel="true" width="500" >
  
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" style="overflow: auto;max-height: 80vh;">
            <el-form-item label="设备名称" prop="equipmentName">
                <el-input v-model="form.equipmentName" :maxlength="8" placeholder="请输入设备名称" />
            </el-form-item>
            <el-form-item label="设备类型" prop="typeId">
                <el-select v-model="form.typeId" placeholder="设备类型">
                    <el-option v-for="dict in typeList" :key="dict.id" :label="dict.typeName" :value="dict.id" />
                </el-select>

            </el-form-item>
            <el-form-item label="设备厂家" prop="manufactorId">
                <el-select v-model="form.manufactorId" placeholder="请输入设备厂家">
                    <el-option v-for="dict in manufactorList" :key="dict.id" :label="dict.manufactorName" :value="dict.id" />
                </el-select>
            </el-form-item>

            <el-form-item label="设备型号" prop="model">
                <el-input v-model="form.model" placeholder="请输入设备型号" />
            </el-form-item>
            <el-form-item label="作用" prop="remark">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入工作作用"></el-input>
            </el-form-item>
            <el-form-item label="设备图片" prop="imgFiles">
                <el-upload ref="uploadRef" :on-exceed="handleExceed" class="avatar-uploader" :on-remove="handleRemove" :on-preview="handlePreview" list-type="picture-card" v-model:file-list="form.imgFiles" :limit="1" :on-change="handleFileChange" :show-file-list="true" accept=".jpg,.png,.svg" action="#" :on-success="handleFileSuccess" :auto-upload="false">
                    <el-icon class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>

            <el-form-item label="输入端">
                <div class="node">
                    <el-button type="primary" plain @click="addNode(1)">新增</el-button>
                    <div class="item" v-for="(item ,index) in form.firstNode" :key="index">
                        <el-select v-model="item['nodeEquipmentType']" placeholder="设备类型">
                            <template v-for="dict in typeList" :key="dict.id">
                                <el-option :label="dict.typeName" :value="dict.id" v-if="(! form.firstNode.some(f=>f.nodeEquipmentType ==dict.id)) ||(item['nodeEquipmentType'] ==dict.id) " />
                            </template>
                        </el-select>
                        <el-input v-model="item['nodeNum']" type="number" :min="1" placeholder="请输入关联数量" />
                        <el-button type="danger" plain @click="delNode(index,1)">删除</el-button>
                    </div>
                </div>
            </el-form-item>
            <el-form-item label="输出端">
                <div class="node">
                    <el-button type="primary" plain @click="addNode(2)">新增</el-button>
                    <div class="item" v-for="(item ,index) in form.afterNode" :key="index">
                        <el-select v-model="item['nodeEquipmentType']" placeholder="设备类型">
                            <template v-for="dict in typeList">
                                <el-option :label="dict.typeName" :value="dict.id" v-if="(! form.afterNode.some(f=>f.nodeEquipmentType ==dict.id)) ||(item['nodeEquipmentType'] ==dict.id) " />
                            </template>
                        </el-select>

                        <el-input v-model="item['nodeNum']" type="number" :min="1" placeholder="请输入关联数量" />
                        <el-button type="danger" plain @click="delNode(index,2)">删除</el-button>
                    </div>
                </div>
            </el-form-item>
            <el-form-item label="模型文件" prop="files">
                <el-upload v-model:file-list="form.files" :limit="1" accept=".glb" :headers="upload.headers" :action="upload.url" :on-success="handleFileSuccess" :auto-upload="true">
                    <!-- <el-icon class="el-icon--upload">
                        <upload-filled />
                    </el-icon>
                    <div class="el-upload__text">将模型文件拖到此处，或<em>点击上传</em></div>                -->
                    <template #trigger>
                        <el-button type="success">点击上传</el-button>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item label="模型大小" prop="size">
                <el-input v-model="form.size" placeholder="请输入模型大小" />
            </el-form-item>
            <el-form-item label="模型方向" prop="rotation">
                <el-input v-model="form.rotation" placeholder="请输入模型方向" />
            </el-form-item>
        </el-form>
        <el-image-viewer v-if="dialogVisible" w-full :url-list="[form.files[0].url]" @close="dialogVisible = false" />

    </Dialog>
</template>
  
<script setup>
import { getEquipment, addEquipment, updateEquipment, uploadImg } from "@/api/simulation/equipment.js";
import { getManufactorByPage, } from "@/api/simulation/manufacturers.js";
import { getEquipmentTypeByPage, } from "@/api/simulation/equipmentType.js";
import { ref, getCurrentInstance, watch } from "vue";
import { getToken } from "@/utils/auth";
import { genFileId } from 'element-plus'
const { proxy } = getCurrentInstance();
const { sys_equipment_type } = proxy.useDict("sys_equipment_type");
const emits = defineEmits(["confirm"]);
defineExpose({ open });
const dialogRef = ref(null);
const form = ref(null);
const formRef = ref(null);
const uploadRef = ref(null);
const title = ref("设备");
const manufactorList = ref([]);//厂商列表
const typeList = ref([]);//设备类型列表
const dialogVisible = ref(false)
const rules = ref({
    typeId: [{ required: true, message: '设备类型不能为空', trigger: 'change' }],
    equipmentName: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
    manufactorId: [{ required: true, message: '设备厂家不能为空', trigger: 'change' }],
    model: [{ required: true, message: '设备型号不能为空', trigger: 'blur' }],
    size: [{ required: true, message: '模型大小不能为空', trigger: 'blur' }],
    rotation: [{ required: true, message: '模型方向不能为空', trigger: 'blur' }],
    remark: [{ required: true, message: '作用不能为空', trigger: 'blur' }],
    files: [{ required: true, message: '模型文件不能为空', trigger: 'change' }],
    imgFiles: [{ required: true, message: '设备图片不能为空', trigger: 'change' }],
})

//模型文件
const upload = reactive({
    // 是否禁用上传
    isUploading: false,
    // 设置上传的请求头部
    headers: { Authorization: "Bearer " + getToken() },
    // 上传的地址
    url: import.meta.env.VITE_APP_BASE_API + "/common/upload"
});


/**
 * 打开弹框
 */
async function open(params) {
    reset();
    // 打开弹框
    await dialogRef.value.open();
    if (params) {
        title.value = "编辑";
        getData(params.id);
    } else {
        title.value = "新增";
    }
}

function handlePreview(uploadFile) {
    dialogVisible.value = true
}

function handleExceed(files) {
    uploadRef.value.clearFiles()
    const file = files[0]
    file.uid = genFileId()
    uploadRef.value.handleStart(file)
}

function handleRemove(file) {
    form.value.imgVos = [];
    form.value.imgfiles = [];
}

/**
 * 文件更改 上传
 * @param file 
 * @param fileList 
 */
function handleFileChange(file, fileList) {
    const formData = new FormData();
    formData.append('equipmentImgFile', file.raw);
    uploadImg(formData).then(res => {
        if (res.code == 200) {
            form.value.imgVos = [{
                name: res.data.fileName,
                url: res.data.url
            }]
        }
    })

}


/**
 * 获取详情
 * @param id 
 */
async function getData(id) {
    try {
        dialogRef.value.showLoading();
        const res = await getEquipment({ id: id });
        form.value = res.data;
        if (form.value.imgVos.length) {
            form.value['imgFiles'] = [{ name: form.value.imgVos[0].name, url: import.meta.env.VITE_APP_BASE_API + form.value.imgVos[0].url }]

        }
    } catch (e) {
        console.error(e);
    } finally {
        dialogRef.value.hideLoading();
    }
}

/**
 * 文件上传成功 
 * @param response 
 * @param file 
 * @param fileList 
 */
function handleFileSuccess(response, file, fileList) {
    if (response.code == 200) {
        form.value.files = [{
            name: response.newFileName,
            url: response.fileName
        }]
    }
}



/**
 * 添加关联节点
 * @param type 
 */
function addNode(type) {
    if (type == 1) {
        if (form.value.firstNode.every(i => i.nodeEquipmentType)) {
            form.value.firstNode.push({
                nodeEquipmentType: null,
                nodeNum: 1,
                nodeType: '0'
            })
        }
    } else {
        if (form.value.afterNode.every(i => i.nodeEquipmentType)) {
            form.value.afterNode.push({
                nodeEquipmentType: null,
                nodeNum: 1,
                nodeType: '1'
            })
        }
        
    }
}

/**
 * 删除节点
 * @param index 
 */
function delNode(index, type) {
    if (type == 1) {
        form.value.firstNode.splice(index, 1)
    } else {
        form.value.afterNode.splice(index, 1)
    }
}


// 表单重置
function reset() {
    form.value = {
        equipmentName: null,
        manufactorId: null,
        model: null,
        firstNode: [],
        afterNode: [],
        typeId: null,
        size: "1,1,1",
        rotation: "0,0,0",
        files: [],
        imgVos: [],
        imgFiles: []
    }
}

/**
 * 确定
 */
function submit() {

    formRef.value.validate(async (valid) => {
        if (valid) {
            try {
                dialogRef.value.showLoading();
                if (form.value.id) {
                    await updateEquipment(form.value);
                } else {
                    await addEquipment(form.value);
                }
                proxy.$modal.msgSuccess("操作成功");
                emits("refresh");
                dialogRef.value.close();
            } catch (e) {
                console.error(e);
            } finally {
                dialogRef.value.hideLoading();
            }
        }
    });
}

/**
 * 获取下拉选项列表
 */
async function getOpetions() {
    //获取厂商列表和设备类型列表
    const res = await Promise.all([getManufactorByPage({
        pageNum: 1,
        pageSize: 500,
    }), getEquipmentTypeByPage({
        pageNum: 1,
        pageSize: 500,
    })])
    manufactorList.value = res[0].data.list;
    typeList.value = res[1].data.list;

}
getOpetions()
 </script>
<style lang="scss" scoped>
.node {
    width: 100%;
    max-height: 100px;
    overflow: auto;
    .item {
        margin: 2px 0;
        display: flex;
    }
}
</style>
  
  